<?php

namespace app\controller;

use app\BaseController;
use app\model\AdminModel;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\middleware\Check;
use think\response\Json;
use think\validate\ValidateRule;

/**
 * Class Order 管理端 统计类控制器
 * @package app\controller
 */
class Statistical extends BaseController
{
    protected $middleware = [Check::class];

    /**获取订单列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function orderList(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['start'] = $request->post('start');//起始时间
            $input['end'] = $request->post('end');//结束时间
            $input['limit'] = $request->post('limit');//每页显示数量
            $input['page'] = $request->post('page');//当前页
            // 参数校验
            $validate = Validate::rule([
                'limit' => ValidateRule::isRequire(null, '缺少参数'),
                'page' => ValidateRule::isRequire(null, '缺少参数'),
                'start' => function ($value) {
                    return $value === null ? '缺少参数' : true;
                },
                'end' => function ($value) {
                    return $value === null ? '缺少参数' : true;
                }
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [];
            if ($adminInfo['type'] == 4) {
                //判断上级类型
                $info = Db::table('eb_admin')->field('id,type')->where('id', $adminInfo['pid'])->find();
                if (!$info) return jsonFail('未找到数据');
                $adminInfo['id'] = $info['id'];
                $adminInfo['type'] = $info['type'];
            }
            switch ($adminInfo['type']) {
                case 1: // 超管
                    $field = 'id,order_no,total_price,delivery_price,goods_price,company_price,plat_price,operate_price,store_price,pid_price,company_status,plat_status,operate_status,status,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time,pay_type,send_status';
                    break;
                case 2: // 平台方
                    $map[] = ['plat_id', '=', $adminInfo['id']];
                    $field = 'id,order_no,total_price,delivery_price,goods_price,plat_price,operate_price,store_price,pid_price,company_status,plat_status,operate_status,status,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time,pay_type,send_status';
                    break;
                case 3: // 运营方
                    $map[] = ['operate_id', '=', $adminInfo['id']];
                    $field = 'id,order_no,total_price,delivery_price,goods_price,operate_price,store_price,pid_price,company_status,plat_status,operate_status,status,is_pay,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time,pay_type,send_status';
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            if ($input['start'] != '') $map[] = ['create_time', '>=', strtotime($input['start'])];
            if ($input['end'] != '') $map[] = ['create_time', '<=', strtotime($input['end'])];
            $table = Db::table('eb_order')->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (\Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**订单划账明细
     * @param Request $request
     * @return \think\response\Json
     */
    public function drawInfo(Request $request)
    {
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['start'] = $request->post('start');//起始时间
            $input['end'] = $request->post('end');//结束时间
            $input['type'] = $request->post('type');// 划账类型
            // 参数校验
            $validate = Validate::rule([
                'start' => ValidateRule::isRequire(null, '缺少参数'),
                'end' => ValidateRule::isRequire(null, '缺少参数'),
                'type' => ValidateRule::isRequire(null, '缺少参数')
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1]);
            if ($adminInfo instanceof Json) return $adminInfo;
            if ($adminInfo['type'] == 4) {
                //判断上级类型
                $info = Db::table('eb_admin')->field('id,type')->where('id', $adminInfo['pid'])->find();
                if (!$info) return jsonFail('未找到数据');
                $adminInfo['id'] = $info['id'];
                $adminInfo['type'] = $info['type'];
            }
            $map = [
                ['o.status', 'in', [6,7]],
                ['is_pay', '=', 1]
            ];
            $table = Db::table('eb_order')->alias('o');
            switch ($adminInfo['type']) {
                case 1: // 超管
                    if ($input['type'] == 1) {
                        // 给平台划账
                        $field = 'sum(total_price - company_price  - pid_price) as money, a.name as name, a.bank_no,a.bank_name,group_concat(o.id) as order_ids';
                        $map[] = ['company_status', '=', 0];
                        $map[] = ['a.is_depend', '=', 1];
                        $group = 'o.plat_id';
                        $table->join(['eb_admin' => 'a'], 'a.id = o.plat_id');
                    } elseif ($input['type'] == 2) {
                        // 给运营商划账
                        $field = 'sum(plat_price) as plat_money,sum(operate_price + store_price + delivery_price) as operate_money, p.name as plat_name, p.bank_no as plat_bank_no,p.bank_name as plat_bank_name, op.name as operate_name, op.bank_no as operate_bank_no,op.bank_name as operate_bank_name,group_concat(o.id) as order_ids';
                        $map[] = ['company_status', '=', 0];
                        $map[] = ['p.is_depend', '=', 0];
                        $group = 'o.operate_id';
                        $table->join(['eb_admin' => 'p'], 'p.id = o.plat_id');
                        $table->join(['eb_admin' => 'op'], 'op.id = o.operate_id');
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                case 2: // 平台给运营划账
                    $map[] = ['company_status', '=', 1];
                    $map[] = ['plat_status', '=', 0];
                    $map[] = ['plat_id', '=', $adminInfo['id']];
                    $field = 'sum(operate_price + store_price + delivery_price) as money, op.name as operate_name, op.bank_no as operate_bank_no,op.bank_name as operate_bank_name,group_concat(o.id) as order_ids';
                    $group = 'o.operate_id';
                    $table->join(['eb_admin' => 'op'], 'op.id = o.operate_id');
                    break;
                case 3: // 运营方
                    $map[] = ['company_status', '=', 1];
                    $map[] = ['plat_status', '=', 1];
                    $map[] = ['operate_id', '=', $adminInfo['id']];
                    if ($input['type'] == 4) {
                        $map[] = ['operate_status', '=', 0];
                        $field = 'sum(store_price) as money, s.shop_name, s.bank_no as bank_no,s.bank_address as bank_address,group_concat(o.id) as order_ids';
                        $group = 'o.store_id';
                        $table->join(['eb_store' => 's'], 's.id = o.store_id');
                    } else if($input['type'] == 5) {
                        $map[] = ['send_status', '=', 0];
                        $field = 'sum(delivery_price) as money,u.name, u.bank_no,u.bank_name,group_concat(o.id) as order_ids';
                        $group = 'o.send_id';
                        $table->join(['eb_user' => 'u'], 'u.id = o.send_id');
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            if ($input['start'] != '') $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            if ($input['end'] != '') $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            $info = $table->field($field)->where($map)->group($group)->select()->toArray();
            if ($info == []) return jsonFail('没有可划账的订单');
            // 整理数据
            return jsonSuccess('获取成功', ['info' => $info]);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return jsonFail('服务内部错误~');
        }
    }

    /**订单划账
     * @param Request $request
     * @return \think\response\Json
     */
    public function draw(Request $request)
    {
        $flag = false;
        try {
            if (!request()->isPost()) return jsonFail('请采用正确的方式登录!');
            // 获取参数
            $input['type'] = $request->post('type');// 划账类型
            $input['data'] = $request->post('data');// 更改记录
            // 参数校验
            $validate = Validate::rule([
                'type' => ValidateRule::isRequire(null, '缺少参数3'),
                'data' => ValidateRule::isRequire(null, '缺少参数4')
            ]);

            if (!$validate->check($input)) {
                return jsonFail($validate->getError());
            }
            // 获取管理员信息
            $adminInfo = AdminModel::getInfo($request->post('token'), [1]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $ids = implode(',', $input['data']);
            $map = [
                ['status', 'in', [6,7]],
                ['is_pay', '=', 1],
                ['id', 'in', $ids]
            ];

            $table = Db::table('eb_order');
            switch ($adminInfo['type']) {
                case 1: // 超管
                    if ($input['type'] == 1) {
                        // 超管给平台直接划账
                        $map[] = ['company_status', '=', 0];
                        $update = ['company_status' => 1];
                    }elseif ($input['type'] ==2) {
                        // 超管给运营商直接划账
                        $map[] = ['company_status', '=', 0];
                        $update = ['company_status' => 1,'plat_status' => 1];
                    } else {
                        return jsonFail('非法操作');
                    }
                    break;
                case 2: // 平台方给运营划账
                    $map[] = ['company_status', '=', 1];
                    $map[] = ['plat_status', '=', 0];
                    $map[] = ['plat_id', '=', $adminInfo['id']];
                    $update = ['plat_status' => 1];
                    break;
                case 3: // 运营方
                    $map[] = ['company_status', '=', 1];
                    $map[] = ['plat_status', '=', 1];
                    $map[] = ['operate_id', '=', $adminInfo['id']];
                    if ($input['type'] == 4 ) {
                        $map[] = ['operate_status', '=', 0];
                        $update = ['operate_status' => 1];
                    }elseif($input['type'] == 5) {
                        $map[] = ['send_status', '=', 0];
                        $update = ['send_status' => 1];
                    } else {
                        return jsonFail('非法数据');
                    }
                    break;
                default:
                    return jsonFail('不合法的数据');
                    break;
            }
            Db::startTrans();
            $flag = true;
            $rtn = $table->where($map)->update($update);
            if ($rtn == count(explode(',', $ids))) {
                Db::commit();
                $flag = false;
                return jsonSuccess('划账成功');
            }
            Db::rollback();
            return jsonFail('划账失败,刷新页面重试');
        } catch (\Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
}
